<template>
  <div class="add_student">
    <div class="common_bg"></div>
    
    <div class="container">
      <div class="card base_card">
        <div class="card_title_box">
          <div class="card_title">
            <i class="icon_base_info"></i>
            <span>基本信息</span>
          </div>
          <!-- <van-divider /> -->
        </div>

        <div class="base_form">
          <ul class="form_list">
            <li><van-field v-model="formData.studentName" label="学员" placeholder="请输入姓名" /></li>
            <li @click="clcikShowBottomArea('sex')">
              <van-cell :value="formData.sexLabel" is-link>
                <template slot="title">
                  <span class="custom-title">性别</span>
                </template>
              </van-cell>
            </li>
            <li @click="clcikShowBottomArea('birthday')">
              <van-cell :value="formData.birthday" is-link>
                <template slot="title">
                  <span class="custom-title">生日</span>
                </template>
              </van-cell>
            </li>
            <li @click="clcikShowBottomArea('grade')">
              <van-cell :value="formData.gradeLabel" is-link>
                <template slot="title">
                  <span class="custom-title">年级</span>
                </template>
              </van-cell>
            </li>
          </ul>
        </div>
      </div>

      <div class="card parent_card"  v-for="(item, index) in formData.bmStudentParentList" :key="index">
        <van-swipe-cell>
          <div class="base_form">
            <ul class="form_list">
              <li><van-field v-model="formData.bmStudentParentList[index].linkPerson" label="家长" placeholder="请输入家长姓名" /></li>
              <li @click="clcikShowBottomArea('parentalStatus', index)">
                <van-cell :value="formData.bmStudentParentList[index].parentalStatusName" is-link >
                  <template slot="title">
                    <span class="custom-title">关系</span>
                  </template>
                </van-cell>
              </li>
              <li><van-field v-model="formData.bmStudentParentList[index].linkPhone" maxLength="11" label="电话" :placeholder="index == 0 ? '请输入电话(必填)' : '请输入电话'" /></li>
              <li><van-field v-model="formData.bmStudentParentList[index].wechat" label="微信" placeholder="请输入微信" /></li>
            </ul>
            <div class="add_parent" @click="addParentCard" v-if="index == formData.bmStudentParentList.length - 1">
              <i class="icon_add2"></i>
              <span>添加家长</span>
            </div>
          </div>

          <template slot="right">
            <van-button square type="danger" text="删除" @click="deleteParent(item, index)" />
          </template>
        </van-swipe-cell>
        
      </div>

      <div class="card intention_card">
        <div class="card_title card_title_box ">
          <i class="icon_intention"></i>
          <span>意向信息</span>
        </div>

        <div class="intention_content">
          <div class="school_area area">
            <van-button @click="clcikShowBottomArea('school')" size="mini" color="#FFC834" round type="info">所属校区</van-button>
            <span class="school_name">{{formData.schoolName || '请选择'}}</span>
          </div>
          <div class="clas_area area">
            <van-button @click="clcikShowBottomArea('class')" size="mini" color="#FFC834" round type="info">意向课程</van-button>
            <span class="school_name" v-html="formData.productName || '请选择'"></span>
          </div>
        </div>
      </div>

      <div class="more_info" @click="toMoreInfo">
        更多资料>>
      </div>
    </div>

    <div class="icon_place update" v-if="$route.meta.title == '学员信息'" @click="updateSubmit"></div>
    <div class="icon_place add" v-else @click="submit"></div>

    <div class="popup">
      <van-popup v-model="showBottomArea" position="bottom" :style="{ height: '40%' }">
        <van-datetime-picker
          v-if="bottomType == 'date'"
          v-model="currentDate"
          type="date"
          :formatter="formatter"
          @cancel="onCancel"
          @confirm="onConfirm"
        />

        <van-picker
          v-else
          show-toolbar
          title="请选择"
          value-key="label"
          :columns="bottomAreaList"
          @cancel="onCancel"
          @confirm="onConfirm"
        />

        
      </van-popup>
    </div>

    <van-popup v-model="showMoreInfo" class="more_info_pop"  position="right" :style="{ height: '100%',width: '100%', }">
      <div class="top_bar pop_top_bar">
        <span class="icon_left" @click="showMoreInfo = false;"></span>
        <span class="title">更多资料录入</span>
        <span @click="showMoreInfo = false;">保存</span>
      </div>
      <div class="common_bg"></div>
      <div class="container">
        <div class="card base_card">
          <div class="card_title_box">
            <div class="card_title">
              <i class="icon_family_info"></i>
              <span>家庭信息</span>
            </div>
          </div>

          <div class="base_form">
            <ul class="form_list">
              <li><van-field v-model="formData.address" label="家庭住址" placeholder="请输入家庭住址" /></li>
              <li><van-field v-model="formData.occupation" label="职业" placeholder="请输入职业" /></li>
              <li><van-field v-model="formData.createTime" label="录入时间" :placeholder="nowDate"  disabled /></li>
            </ul>
          </div>
        </div>


        <div class="card parent_card" style="margin: .5333rem 0;">
          <div class="card_title_box">
            <div class="card_title">
              <i class="icon_sale"></i>
              <span>销售信息</span>
            </div>
          </div>

          <div class="base_form">
            <ul class="form_list">
              <li @click="showRightPop('marketPerson')">
                <van-cell :value="formData.marketPerson.employeesName" is-link >
                  <template slot="title">
                    <span class="custom-title">市场人员</span>
                  </template>
                </van-cell>
              </li>
              <li @click="showRightPop('salePerson')">
                <van-cell :value="formData.salePerson.employeesName" is-link >
                  <template slot="title">
                    <span class="custom-title">课程顾问</span>
                  </template>
                </van-cell>
              </li>
              <li @click="showRightPop('source')">
                <van-cell :value="formData.source.sourceLabel" is-link >
                  <template slot="title">
                    <span class="custom-title">客户来源</span>
                  </template>
                </van-cell>
              </li>
              <li @click="showRightPop('tag')">
                <van-cell :value="formData.tag.tagLabel" is-link >
                  <template slot="title">
                    <span class="custom-title">用户标签</span>
                  </template>
                </van-cell>
              </li>
            </ul>
          </div>
        </div>


        <div class="card intention_card" style="margin-top: 0">
          <div class="card_title card_title_box ">
            <i class="icon_remark"></i>
            <span>备注</span>
          </div>

          <div class="remark_content">
            <div>
              <van-field
                v-model="formData.remark"
                rows="3"
                autosize
                type="textarea"
                maxlength="140"
                placeholder="请输入备注"
                show-word-limit
                style="text-align:left"
              />
            </div>
          </div>
        </div>
      </div>
    </van-popup>

    <van-popup v-model="rightPopupStatus" class="screen_box" position="right" :style="{ height: '85%' }">
      <div class="screen_title_box">
        <i class="icon_return" @click="rightPopupStatus = false;"></i>
        <span class="screen_title">{{activeRightPopupTitle}}</span>
        <span class="btn_confirm" @click="rightPopConfirm">确定</span>
        <!-- <span class="btn_confirm btn_add" @click="showAddPop = true;">添加</span> -->
      </div>


      <div class="search_list">
        <van-checkbox-group v-model="checkedList">
          <van-cell-group>
            <van-cell
              v-for="(item, index) in rightPopupList"
              clickable
              :key="item.id"
              :title="item.label"
              @click="toggle(index)"
            >
              <van-checkbox
                :name="item.id"
                ref="checkboxes"
                slot="right-icon"
              />
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
      </div>


      
    </van-popup>

    <van-dialog
      v-model="showAddPop"
      title="添加"
      show-cancel-button
      class="dialog"
    >
      <van-field v-model="formData.studentName" placeholder="请输入" />
    </van-dialog>

  </div>
</template>

<style>
.add_student .dialog input {
  text-align: center !important;
}
.add_student .remark_content .van-cell {
  background: #fff8e5;
  border-radius:.373333rem;
}
.add_student textarea {
  text-align: left !important;
}

.add_student .van-divider {
  margin: 0px 0;
}

.add_student .van-cell {
  /* border-radius: 0 .266667rem .266667rem 0; */
}
.add_student .van-field__control {
  text-align: right;
}
.add_student .parent_card .van-swipe-cell{
  border-radius: 0 .2rem .2rem 0;
  /* box-sizing: border-box;
  overflow: hidden; */
}
.add_student .parent_card .van-swipe-cell button{
  height: 100%;
  border-radius: 0 .2rem .2rem 0;
}

.add_student .base_form li:first-child .van-cell{
  border-radius: 0 .266667rem 0 0;
}
.add_student .base_form li:last-child .van-cell {
  border-radius: 0  0 .266667rem 0;
}


</style>
<style scoped>
.add_student .more_info_pop {
  /* padding-bottom: .8rem; */
}
.add_student .remark_content > div {
  padding: .4rem;
}

.add_student .icon_family_info {
  display: inline-block;
  width: .52rem;
  height: .626667rem;
  background: url('../../../assets/img/icon_family.png') 0 0 no-repeat;
  background-size: 100%;
}
.add_student .icon_sale {
  display: inline-block;
  width: .586667rem;
  height: .586667rem;
  background: url('../../../assets/img/icon_sale.png') 0 0 no-repeat;
  background-size: 100%;
}



.add_student .container {
  position: relative;
  padding: .4rem .266667rem 0;
}

/* .add_student  */
.add_student .parent_card {
  width: 100%;
  /* min-height: 7.06rem; */
  box-shadow:0px 0px 4px 3px rgba(216,216,216,0.5);
  border-left: .186667rem solid #FFC834;
  background: #fff;
  border-radius: .2rem;
  box-sizing: border-box;
  z-index: 99;
  overflow: hidden;
}
.add_student .intention_card {
  width: 100%;
  /* min-height: 7.06rem; */
  box-shadow:0px 0px 4px 3px rgba(216,216,216,0.5);
  border-left: .186667rem solid #FE8697;
  background: #fff;
  border-radius: .2rem;
  box-sizing: border-box;
  z-index: 99;
  margin-top: .773333rem;
  margin-bottom: .4rem;
}


.add_student .icon_base_info {
  display: inline-block;
  width: .586667rem;
  height: .52rem;
  background: url('../../../assets/img/icon_base_info.png') 0 0 no-repeat;
  background-size: 100%;
}


.add_student .card {
  /* padding: 0 .133333rem; */
  box-sizing: border-box;
  overflow: hidden;
}


.add_student .base_form {
  /* margin-top: .133333rem; */
}

.add_student .form_list li {
  position: relative;
}
.add_student .form_list li:first-child{
  border-top: none;
}

.add_student .form_list li:after {
  content: " ";
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 1px;
  border-top: 1px solid #e9e9e9 !important;
  -webkit-transform: scaleY(.5);
  transform:scaleY(.5);
}

.parent_card .form_list li:first-child:after {
  content: "";
  border-top: none !important;
}

.add_student .parent_card {
  margin-top: .266667rem;
  overflow: hidden;
}

.add_student .icon_intention {
  width: .746667rem;
  height: .746667rem;
  display: inline-block;
  background: url('../../../assets/img/icon_intention.png') 0 0 no-repeat;
  background-size: 100%;
}

.add_student .intention_content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 2.666667rem;
}
.add_student .intention_content > div {
  text-align: center;
}
.add_student .intention_content > div button {
  width: 1.84rem;
  height: .64rem;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  font-size: .32rem;
  box-shadow:0px 0px 2px 2px rgba(210,208,208,0.5);
}
.add_student .intention_content .school_name {
  color: #666660;
  font-size: .32rem;
  display: block;
  margin-top: .266667rem;
}

.add_student .school_area {
  border-right: .5px solid #D2D2D2;
}
.add_student .area {
  width: 50%;
  /* display: flex;
  justify-content: center;
  flex-wrap: nowrap; */
}

.add_student .add_parent {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: .266667rem;
  padding-bottom: .2rem;
  margin-top: .133333rem;
  margin-left: -2px;
}

.add_student .add_parent span {
  color: #FFC834;
  font-size: .32rem;
}


li {
  /* border-bottom: 1px solid #e9e9e9 */
}

</style>

<script>
import {
  createNamespacedHelpers
} from "vuex";
let {
  mapState,
  mapGetters,
  mapMutations,
  mapActions
} = createNamespacedHelpers("addStudent");

export default {
  data() {
    return {
      jwtAuth: {},
      currentDate: new Date(),
      formData: {
        studentName: '',
        sex: '',
        sexLabel: '请选择',
        birthday: '请选择',
        grade: '',
        gradeLabel: '请选择',
        bmStudentParentList: [
          {
            linkPerson: '',
            linkPhone: '',
            wechat: '',
            parentalStatus: '',
            parentalStatusName: '请选择',
          }
        ],
        address: '',
        occupation: '',
        remark: '',
        schoolId: '',
        schoolName: '',
        productId: [],
        productName: '',
        marketPerson: {
          employeesId: "",
          employeesName: "请选择",
          employeesType: "15",
        },
        salePerson: {
          employeesId: "",
          employeesName: "请选择",
          employeesType: "5",
        },
        bmStudentEmployeesList: [
          {
            employeesId: "",
            employeesName: "",
            employeesType: "",
          }
        ],

        source: {
          sourceId: '',
          sourceLabel: '请选择',
        },
        tag: {
          tagId: '',
          tagLabel: '请选择',
        },
        bmStudentCustomerList: [
          {
            customerId: "",
            customerRemark: "",
          }
        ],
        bmStudentLabelList: [
          {
            labelManagementId: "",
            labelManagementName: "",
          }
        ],
      },
      bottomType: '',
      showBottomArea: false,
      bottomAreaType: '',

      showMoreInfo: false,
      rightPopupStatus: false,
      showAddPop: false,

      activeRightPopupTitle: '',
      
      bottomAreaList: [],
      rightPopupList: [],

      sexList: [
        {
          label: '男',
          id: 1
        },
        {
          label: '女',
          id: 2
        },
      ],
      relationShipList: [],
      schoolList: [],

      checkedList: [],
      productList: [
      ],

      marketPersonList: [],
      salePersonList: [],
      sourceList: [],
      tagList: [],
      parentIndex: 0,
      productIdArr: [],
    }
  },

  beforeRouteEnter (to, from, next) {
    console.log(from);
    if(from.params.id) {
      to.meta.title = '学员信息';
      next();
    }else{
      to.meta.title = '添加学员';
      next();
    }
  },

  created() {
    this.jwtAuth = JSON.parse(sessionStorage.getItem('jwtAuth'));
    this.queryAllSchool();
    this.queryAllGrade();
    this.queryAllRelationship();

    console.log(this.$route.meta.title)
    if(this.$route.params.id) {
      this.initStudentInfo();
    }else{

    }

    // console.log(this.jwtAuth);
  },
  methods: {
     ...mapMutations([
      "updateInfo",
    ]),
    ...mapActions([
      "formGet",
      "post"
    ]),

    submit() {
      let data = {};
      Object.assign(data, this.formData);
      console.log(data.productId)

      data.bmStudentProductList = [];
      data.bmStudentEmployeesList = [];
      data.bmStudentCustomerList = [];    // 客户来源
      data.bmStudentLabelList = [];       // 标签

      if(data.productId.length > 0) {
        data.productId.forEach((item, index) => {
          let obj = {
            productId: item,
            productName: data.productName.split(',')[index]
          }
          data.bmStudentProductList.push(obj);
        })
      }

      if(data.salePerson.employeesId) {
        data.salePerson.employeesId.forEach((item, index) => {
          let obj = {
            employeesId: item,
            employeesName: data.salePerson.employeesName.split(',')[index],
            employeesType: "5"
          }
          data.bmStudentEmployeesList.push(obj);
        })
      }
      if(data.marketPerson.employeesId) {
        data.marketPerson.employeesId.forEach((item, index) => {
          let obj = {
            employeesId: item,
            employeesName: data.marketPerson.employeesName.split(',')[index],
            employeesType: "15"
          }
          data.bmStudentEmployeesList.push(obj);
        })
      }

      if(data.source.sourceId) {
        data.source.sourceId.forEach((item, index) => {
          let obj = {
            customerId: item,
            customerRemark: data.source.sourceLabel.split(',')[index],
          }
          data.bmStudentCustomerList.push(obj);
        })
      }
      if(data.tag.tagId) {
        data.tag.tagId.forEach((item, index) => {
          let obj = {
            labelManagementId: item,
            labelManagementName: data.tag.tagLabel.split(',')[index],
          }
          data.bmStudentLabelList.push(obj);
        })
      }

      if(data.sexLabel == '请选择') {
        data.sexLabel = ''
      }
      if(data.birthday == '请选择') {
        data.birthday = ''
      }
      if(data.gradeLabel == '请选择') {
        data.gradeLabel = ''
      }
      if(data.productName == '请选择') {
        data.productName = ''
      }
      if(data.marketPerson.employeesName == '请选择') {
        data.productName = ''
      }
      if(data.salePerson.employeesName == '请选择') {
        data.productName = ''
      }
      data.bmStudentParentList.forEach(item => {
        if(item.parentalStatusName == '请选择') {
          item.parentalStatusName = ''
        }
      })


      if(!data.studentName) {
        this.$toast.fail('请输入学员姓名');
        return false;
      }
      if (!(/^1[34578]\d{9}$/.test(data.bmStudentParentList[0].linkPhone))) {
        this.$toast.fail('请输入正确电话号码');
        return false;
      }

      if(!this.formData.schoolId) {
        this.$toast.fail('请选择校区');
        return false;
      }

      data.createBy = this.jwtAuth.employeesId;

      // if(!this.formData.salePerson.employeesId) {
      //   this.$toast.fail('请在更多资料中选择课程顾问');
      //   return false;
      // }
      

      console.log(data);
      // return false;

      this.post({
        API: 'insert',
        data: data
      }).then(res => {
        this.$notify({ type: 'success', message: '新增成功',duration: 1200 });
        this.$router.push({
          name: 'student'
        })
      }).catch(err => {
        this.$toast.fail(err);
      })
    },
    updateSubmit() {
      let data = {};
      Object.assign(data, this.formData);
      // data.bmStudentProductList = [];
      data.bmStudentEmployeesList = [];
      // data.bmStudentCustomerList = [];    // 客户来源
      // data.bmStudentLabelList = [];       // 标签

      console.log(data.productId)
      data.bmStudentProductList = [];
      if(data.productId.length > 0) {
        data.productId.forEach((item, index) => {
          let obj = {
            productId: item,
            productName: data.productName.split(',')[index]
          }
          data.bmStudentProductList.push(obj);
        })
      }

      if(data.salePerson.employeesId) {
        data.salePerson.employeesId.forEach((item, index) => {
          let obj = {
            employeesId: item,
            employeesName: data.salePerson.employeesName.split(',')[index],
            employeesType: "5"
          }
          data.bmStudentEmployeesList.push(obj);
        })
      }
      if(data.marketPerson.employeesId) {
        data.marketPerson.employeesId.forEach((item, index) => {
          let obj = {
            employeesId: item,
            employeesName: data.marketPerson.employeesName.split(',')[index],
            employeesType: "15"
          }
          data.bmStudentEmployeesList.push(obj);
        })
      }

      if(data.source.sourceId) {
        data.source.sourceId.forEach((item, index) => {
          let obj = {
            customerId: item,
            customerRemark: data.source.sourceLabel.split(',')[index],
          }
          data.bmStudentCustomerList.push(obj);
        })
      }
      if(data.tag.tagId) {
        data.tag.tagId.forEach((item, index) => {
          let obj = {
            labelManagementId: item,
            labelManagementName: data.tag.tagLabel.split(',')[index],
          }
          data.bmStudentLabelList.push(obj);
        })
      }

      data.studentId = this.$route.params.id;

      this.post({
        API: 'update',
        data: data
      }).then(res => {
        this.$notify({ type: 'success', message: '编辑成功',duration: 1200 });
        this.$router.push({
          name: 'studentDetail',
          id: this.$route.params.id
        })
      })
    },

    initStudentInfo() {
      this.formGet({
        API: 'selectById',
        data: {
          id: this.$route.params.id
        }
      }).then(res => {
        this.settingData(res)
      })
    },

    settingData(res) {
      this.formData.studentName = res.studentName;
      this.formData.sexLabel = res.sex == 1 ? '男' : '女';
      this.formData.birthday = res.birthday;
      this.formData.gradeLabel = res.gradeName;
      this.formData.bmStudentParentList = res.bmStudentParentList;
      this.formData.bmStudentProductList = res.bmStudentProductList;
      this.formData.bmStudentLabelList = res.bmStudentLabelList;
      this.formData.bmStudentEmployeesList = res.bmStudentEmployeesList;
      this.formData.bmStudentCustomerList = res.bmStudentCustomerList;
      this.formData.bmFollowList = res.bmFollowList;
      this.formData.bmAuditionStudentList = res.bmAuditionStudentList;

      this.formData.schoolName = res.schoolName;
      this.formData.schoolId = res.schoolId;
      let str = ''
      res.bmStudentProductList.forEach(item => {
        str += item.productName + '</br>';
      })
      this.formData.productName = str;
      
      this.formData.address = res.address;
      this.formData.occupation = res.occupation;
      this.formData.createTime = res.createTime;

      let salePersonStrArr = []
      let marketPersonArr = []

      res.bmStudentEmployeesList.forEach(item => {
        if(item.employeesType == 5) {
          salePersonStrArr.push(item.employeesName);
        }
        if(item.employeesType == 15) {
          marketPersonArr.push(item.employeesName);
        }
      })
      this.formData.marketPerson.employeesName = marketPersonArr.join(',');
      this.formData.salePerson.employeesName = salePersonStrArr.join(',');

      this.productIdArr = [];
      res.bmStudentProductList.forEach(item => {
        this.productIdArr.push(item.productId);
      })

      // this.checkedList = this.productIdArr;

      let sourceArr = [];
      let tagArr = [];

      res.bmStudentCustomerList.forEach(item => {
        sourceArr.push(item.customerRemark)
      })
      res.bmStudentLabelList.forEach(item => {
        tagArr.push(item.labelManagementName)
      })
      this.formData.source.sourceLabel = sourceArr.join(',');
      this.formData.tag.tagLabel = tagArr.join(',')

      this.formData.remark = res.remark;

    },




    rightPopConfirm() {
      console.log(this.bottomAreaType)
      switch (this.bottomAreaType) {
        case 'class':
          this.formData.productName = this.showCheckedLabel(this.productList, 'productId', 'productName', this.formData.productId, this.formData.productName);
          this.formData.productId = this.checkedList;
          this.rightPopupStatus = false;
          break;
        case 'marketPerson':
          this.formData.marketPerson.employeesName = this.showCheckedLabel(this.marketPersonList, 'employeesId', 'employeesName', this.formData.marketPerson.employeesId, this.formData.marketPerson.employeesName);
          this.formData.marketPerson.employeesId = this.checkedList;
          this.rightPopupStatus = false;
          break;
        case 'salePerson':
          this.formData.salePerson.employeesName = this.showCheckedLabel(this.salePersonList, 'employeesId', 'employeesName', this.formData.salePerson.employeesId, this.formData.salePerson.employeesName);
          this.formData.salePerson.employeesId = this.checkedList;
          this.rightPopupStatus = false;
          break;
        case 'source':
          this.formData.source.sourceLabel = this.showCheckedLabel(this.sourceList, 'customerId', 'customerRemark', this.formData.source.sourceId, this.formData.source.sourceLabel);
          this.formData.source.sourceId = this.checkedList;
          this.rightPopupStatus = false;
          break;
        case 'tag':
          this.formData.tag.tagLabel = this.showCheckedLabel(this.tagList, 'labelManagementId', 'labelManagementName', this.formData.tag.tagId, this.formData.tag.tagLabel);
          this.formData.tag.tagId = this.checkedList;
          this.rightPopupStatus = false;
          break;

        default:
          break;
      }
    },
    showCheckedLabel(list, checkedId, checkedName,  id, name){
      console.log(this.checkedList)
      let str = [];
      id = this.checkedList;
      this.checkedList.forEach(item => {
        list.filter(val => {
          if(val[checkedId] == item) {
            str.push(val[checkedName]);
          }
        })
      })
      if(str) {
        name = str.join(',');
      }else{
        name = '请选择';
      }
      return name;
    },


    clcikShowBottomArea(type, index) {
      this.bottomAreaType = type;
      this.parentIndex = index;
      console.log(type)
      if(type == 'birthday') {
        this.bottomType = 'date';
      }else{
        this.bottomType = '';
      }

      switch (type) {
        case 'sex':
          this.showBottomArea = true;
          this.bottomAreaList = this.sexList;
          break;
        case 'birthday':
          this.showBottomArea = true;
          break;
        case 'parentalStatus':
          this.showBottomArea = true;
          this.bottomAreaList = this.relationShipList;
          break;
        case 'school':
          this.showBottomArea = true;
          this.bottomAreaList = this.schoolList;
          break;
        case 'grade':
          this.showBottomArea = true;
          this.bottomAreaList = this.gradeList;
          break;
        case 'class':
          this.queryAllSubject();
          this.activeRightPopupTitle = '意向课程';
          this.rightPopupStatus = true;

          if(this.productIdArr.length > 0) {
            this.checkedList = [];
            this.checkedList = this.productIdArr;
          }
          break;
      
        default:
          break;
      }
    },

    showRightPop(type) {
      this.rightPopupStatus = true;
      this.checkedList= []
      this.bottomAreaType = type;
      switch (type) {
        case 'marketPerson':
          this.activeRightPopupTitle = '市场人员';
          this.rightPopupList = this.marketPersonList;
          break;
        case 'salePerson':
          this.activeRightPopupTitle = '课程顾问';
          this.rightPopupList = this.salePersonList;
          break;
        case 'source':
          this.activeRightPopupTitle = '客户来源';
          this.rightPopupList = this.sourceList;
          break;
        case 'tag':
          this.activeRightPopupTitle = '标签';
          this.rightPopupList = this.tagList;
          break;
      
        default:
          break;
      }
    },

    onConfirm(value, index) {
      console.log(`当前值：${value.id || value}, 当前索引：${index}`)

      switch (this.bottomAreaType) {
        case 'school':
          this.formData.schoolName = this.schoolList[index].schoolName;
          this.formData.schoolId = this.schoolList[index].schoolId;
          this.formData.productId = '';
          this.checkedList = [];
          this.formData.productName = '请选择';
          break;
        case 'sex':
          this.formData.sex = this.sexList[index].id;
          this.formData.sexLabel = this.sexList[index].label;
          break;
        case 'birthday':
          this.formData.birthday = this.format(this.currentDate);
          break;
        case 'parentalStatus':
          
          this.formData.bmStudentParentList[this.parentIndex].parentalStatus = this.relationShipList[index].id;
          this.formData.bmStudentParentList[this.parentIndex].parentalStatusName = this.relationShipList[index].label;
          break;
        case 'grade':
          this.formData.grade = this.gradeList[index].id;
          this.formData.gradeLabel = this.gradeList[index].label;
          break;
        default:
          break;
      }
      this.showBottomArea = false;
    },
    onCancel() {
      this.showBottomArea = false;
    },

    toggle(index) {
      this.$refs.checkboxes[index].toggle();
    },


    
    queryAllSchool(btnId) {
      let accountId
      this.jwtAuth.schoolId == '' ? accountId = '' : accountId = this.jwtAuth.accountId
      
      this.post({ 
        API: 'queryAllSchool',
        data: {
          accountId: accountId,
          menuId: btnId || 'studentManagement',
          schoolIds: this.jwtAuth.schoolId.split(','),
        }
      }).then(res => {
        res = res.filter(val => {
          return val.schoolId !== '';
        });
        res.map((val) => {
          val.label = val.schoolName;
          val.id = val.schoolId;
        })

        if(btnId) {
          this.powerSchoolList = res
        }else{
          this.schoolList = res
          // this.initData();
        }
      }).catch(err => {
        this.$toast.fail(err);
      })
    },
    queryAllSubject() {
      let data = {
        schoolId: this.formData.schoolId,
      }
      this.formGet({
        API: 'queryProductBySchool',
        data: data
      }).then(res => {
        res.map((val) => {
          val.id = val.productId;
          val.label = val.productName;
        })
        this.productList = res;
        this.rightPopupList = res;
      }).catch(err => {
        this.$toast.fail(err);
      })
    },
    queryAllGrade() {
      this.formGet({ 
        API: 'queryByDicKey',
        data: {
          dicKey: 'grade',
        }
      }).then(res => {
        res.map((val) => {
          val.label = val.dicLabel;
          val.id = val.dicCode;
        })
        this.gradeList = res;
      }).catch(err => {
        this.$toast.fail(err);
      })
    },
    queryAllRelationship() {
      this.formGet({ 
        API: 'queryByDicKey',
        data: {
          dicKey: 'parentRelationship',
        }
      }).then(res => {
        res.map((val) => {
          val.label = val.dicLabel;
          val.id = val.dicCode;
        })
        this.relationShipList = res;
      }).catch(err => {
        this.$toast.fail(err);
      })
    },
    queryAllPerson() {
      this.post({    // 市场
        API: 'queryPositionListBySchoolId',
        data: {
          positionCode: ['15'],
          schoolId: this.formData.schoolId,
        }
      }).then(res => {
        res.map((val) => {
          val.id = val.employeesId;
          val.label = val.employeesName;
        })
        this.marketPersonList = res;
      }).catch(err => {
        this.$toast.fail(err);
      })

      this.post({    // 销售
        API: 'queryPositionListBySchoolId',
        data: {
          positionCode: ['5'],
          schoolId: this.formData.schoolId,
        }
      }).then(res => {
        res.map((val) => {
          val.id = val.employeesId;
          val.label = val.employeesName;
        })
        this.salePersonList = res;
      }).catch(err => {
        this.$toast.fail(err);
      })


      this.post({    // 客户来源
        API: 'selectBmCustomerPageList',
        data: {}
      }).then(res => {
        res.map((val) => {
          val.id = val.customerId;
          val.label = val.customerRemark;
        })
        this.sourceList = res;
      }).catch(err => {
        this.$toast.fail(err);
      })


      this.post({    // 标签
        API: 'selectBmLabelManagementPageList',
        data: {}
      }).then(res => {
        res = res.filter(val => {
          return val.parentId != 0;
        })
        res.map((val) => {
          val.id = val.labelManagementId;
          val.label = val.labelManagementName;
        })
        this.tagList = res;
      }).catch(err => {
        this.$toast.fail(err);
      })



    },

    

    deleteParent(item, index) {
      if(this.formData.bmStudentParentList.length == 1) {
        return false;
      }
      if(this.$route.meta.title == '添加学员') {
        this.formData.bmStudentParentList.splice(index, 1);
      }else{
        console.log(item);
        this.deleteParentCard(item.studentParentId)
      }
    },
    deleteParentCard(id) {
      this.formGet({
        API: 'deleteById',
        data: {
          id: id
        }
      }).then(res => {
        this.$notify({ type: 'success', message: '删除成功',duration: 1200});
        this.initStudentInfo();
      })
    },
    addParentCard() {
      let obj = {
        linkPerson: '',
        linkPhone: '',
        wechat: '',
        parentalStatus: '',
        parentalStatusName: '请选择',
      }
      this.formData.bmStudentParentList.push(obj);
    },

    toMoreInfo() {
      if(!this.formData.schoolId) {
        this.$toast.fail('请选择所属校区');
        return false;
      }
      this.queryAllPerson();
      this.showMoreInfo = true;
    },

    format(date) {
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      if(month < 10) {
        month = `0${month}`
      }
      let day = date.getDate();
      if(day < 10) {
        day = `0${day}`
      }


      return `${year}-${month}-${day}`
    },

    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`
      }
      return value;
    }
  },
  computed: {
    nowDate() {
      let date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      if(month < 10) {
        month = `0${month}`
      }
      let day = date.getDate();

      return `${year}-${month}-${day}`
    }
  }
}
</script>